import React from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { Button, Col, Form, Input, message, Modal, Row, Select, Table } from 'antd';
import styles from './hotQuestion.css';
import EditModal from '../hotSpots/editModal';
import { fetchHotTableData, fetchUserTypeList, fetchRemoveLabel, fetchUpOrDownLabel } from '@/services/hotQuestion';
class HotConfiguration extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      loading: false,
      total: 0,
      current: 1,
      size: 10,
      userList: [],
      labelName: '',
      userTypeId: '',
    };
  }

  componentDidMount() {
    this.getUserTypeList();
    this.getTableData();
  }

  /* 获取用户类型-筛选框 */
  getUserTypeList = async () => {
    const res = await fetchUserTypeList({ current: 1, size: 999999 });
    this.setState({
      userList: res.records ? res.records : [],
    });
  };

  /* 获取表格数据 */
  getTableData = () => {
    this.setState({ loading: true, }, async () => {
      const { current, size, labelName, userTypeId } = this.state;
      const { applicationId } = this.props;
      const res = await fetchHotTableData({ current, size, applicationId, labelName, userTypeId });
      this.setState({
        list: res.records ? res.records : [],
        total: res.total,
        loading: false,
      });
    });
  };

  /* 分页 */
  changePagination = (current, size) => {
    this.setState({ current, size }, () => {
      this.getTableData();
    });
  };

  /* 打开{formatMessage({ id: 'hotSpots.edit' })}框 */
  openModal = row => {
    this.EditModal.initOpen(row);
  };

  /* 条件查询 */
  searchByParams = () => {
    const info = this.props.form.getFieldsValue();
    this.setState(
      {
        current: 1,
        userTypeId: info.userTypeId ? info.userTypeId : '',
        labelName: info.labelName ? info.labelName : '',
      },
      () => {
        this.getTableData();
      }
    );
  };

  /* {formatMessage({ id: 'hotSpots.delete' })}标签确认框 */
  deleteHotLabel = id => {
    const that = this;
    Modal.confirm({
      title: formatMessage({ id: 'hotSpots.confirmDelete' }),
      okText: formatMessage({ id: 'hotSpots.confirm' }),
      okType: 'danger',
      cancelText: formatMessage({ id: 'hotSpots.cancel' }),
      onOk() {
        that.removeLabel(id);
      },
    });
  };

  /* 删除标签 */
  removeLabel = async id => {
    const res = await fetchRemoveLabel({ id });
    const { list, loading, current, total, userList } = this.state;
    if (list.length === 1 && current > 1) {
      this.setState({ current: current - 1 }, () => {
        this.getTableData();
      })
    } else {
      this.getTableData();
    }
    message.info(res.msg);
  };

  /** 上{formatMessage({ id: 'hotSpots.moveDown' })} */
  movePosition = async (row, type) => {
    const { list } = this.state;
    const { applicationId } = this.props;
    const res = await fetchUpOrDownLabel({ id: row.id, type, applicationId })
    message.info(res.msg);
    this.getTableData()
  }

  render() {
    const { list, loading, current, total, userList, size } = this.state;
    const { applicationId } = this.props;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: formatMessage({ id: 'hotSpots.categoryLabel' }),
        dataIndex: 'labelName',
        width: 150,
      },
      {
        title: formatMessage({ id: 'hotSpots.image' }),
        dataIndex: 'imgUrl',
        width: 100,
        render: imgSrc => {
          if (imgSrc) {
            return <img src={imgSrc} style={{ width: 40, height: 40 }} />;
          }
        },
      },
      {
        title: formatMessage({ id: 'hotSpots.applicableUserType' }),
        dataIndex: 'userTypeName',
        width: 350,
        render: userTypeName => {
          const list = userTypeName.split(',');
          return (
            <div className={styles.userTypeBox}>
              {list.map((item, index) => {
                return (
                  <div key={index} className={styles.userTypeItem}>
                    {item}
                  </div>
                );
              })}
            </div>
          );
        },
      },
      {
        title: formatMessage({ id: 'hotSpots.hotQuestionCount' }),
        dataIndex: 'questionCount',
        width: 100,
      },
      {
        title: formatMessage({ id: 'hotSpots.operation' }),
        width: 350,
        render: (text, row, index) => {
          return (
            <div>
              <Button size='small' type='primary' icon='edit' style={{ marginRight: 4 }} onClick={() => this.openModal(row)}>
                {formatMessage({ id: 'hotSpots.edit' })}
              </Button>
              <Button size='small' type='primary' icon='delete' style={{ background: '#E8313B', borderColor: '#E8313B', marginRight: 4 }} onClick={() => this.deleteHotLabel(row.id)}>
                {formatMessage({ id: 'hotSpots.delete' })}
              </Button>
              <Button
                style={{ marginRight: 4, background: current == 1 && index == 0 ? '#BFBFBF' : '#556FB5', color: "#ffffff" }}
                onClick={() => this.movePosition(row, 1)}
                disabled={current == 1 && index == 0}
                icon="arrow-up"
                size="small"
              >
                {formatMessage({ id: 'hotSpots.moveUp' })}
              </Button>
              <Button
                style={{ marginRight: 4, background: ((current - 1) * size + index + 1) == total ? '#BFBFBF' : '#8395FB', color: "#ffffff" }}
                onClick={() => this.movePosition(row, 2)}
                disabled={((current - 1) * size + index + 1) == total}
                icon="arrow-down"
                size="small"
              >
                {formatMessage({ id: 'hotSpots.moveDown' })}
              </Button>
            </div>
          );
        },
      },
    ];

    return (
      <div>
        <Row style={{ marginBottom: 20 }}>
          <Col span={16}>
            <Form layout="inline">
              <Form.Item label={formatMessage({ id: 'hotSpots.categoryLabel' })}>
                {getFieldDecorator('labelName')(
                  <Input.Search placeholder={formatMessage({ id: 'hotSpots.enterKeyword' })} onSearch={this.searchByParams} />
                )}
              </Form.Item>
              <Form.Item label={formatMessage({ id: 'hotSpots.userType' })}>
                {getFieldDecorator('userTypeId', { initialValue: '' })(
                  <Select style={{ width: 200 }}>
                    <Select.Option value={''}>{formatMessage({ id: 'hotSpots.defaultType' })}</Select.Option>
                    {userList.map((item, index) => {
                      return (
                        <Select.Option value={item.id} key={item.id}>{item.tagName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
              <Form.Item>
                <Button type={'primary'} onClick={this.searchByParams}>{formatMessage({ id: 'hotSpots.search' })}</Button>
              </Form.Item>
            </Form>
          </Col>
          <Col span={8} style={{ textAlign: "right" }}>
            <Button type={'primary'} onClick={() => this.openModal()}>{formatMessage({ id: 'hotSpots.add' })}</Button>
            <div style={{ fontSize: '13px', color: "rgba(51, 51, 51, 0.5)", marginTop: 10 }}>{formatMessage({ id: 'hotSpots.channelNote' })}</div>
          </Col>
        </Row>

        <Table
          rowKey={'id'}
          columns={columns}
          dataSource={list}
          loading={loading}
          pagination={{
            total,
            current,
            onChange: this.changePagination,
            showSizeChanger: true,
            showQuickJumper: true,
            onShowSizeChange: this.changePagination,
          }}
          scroll={{ x: 'auto' }}
        />

        <EditModal
          onRef={ref => (this.EditModal = ref)}
          applicationId={applicationId}
          userList={userList}
          refreshTableList={this.getTableData}
        />
      </div>
    );
  }
}

export default Form.create()(HotConfiguration);
